package com.jbm.jbmsupplier.util;

import java.io.OutputStream;

/**
 * Created by root on 16-9-5.
 */
public class PicOutputStream extends OutputStream
{
	protected IUploadMedia ium;
	protected Media rtn;
	protected int offset;
	protected Interface iface;
	protected boolean iseof;
	protected byte[] buffer;

	public PicOutputStream ()
	{
		offset = 0;
		iseof = false;
	}

	public PicOutputStream ( int folderid, String foldertype, Media media, Interface iface )
	{
		this();

		this.ium = new IUploadMedia( folderid, foldertype, media );
		buffer = new byte[Interface.BUFFER_LEN];
		this.iface = iface;
	}

	public void write( int b )
	{
		byte bb[] = new byte[1];
		bb[0] = (byte)(b&0xff);
		write(bb);
	}

	public void write(byte b[])
	{
		write(b,0,b.length);
	}

	public void write(byte b[], int off, int len)
	{
		if (b == null)
		{
			throw new NullPointerException();
		} else if ((off < 0) || (off > b.length) || (len < 0) ||
				((off + len) > b.length) || ((off + len) < 0))
		{
			throw new IndexOutOfBoundsException();
		} else if (len == 0)
		{
			return;
		}

		if (this.iseof)
			return;

		int rlen = 0;
		do
		{
			if ( offset == Interface.BUFFER_LEN )
			{
				ium.buffer = this.buffer;
				ium.bufferlen = offset;
				offset = 0;
				rtn = iface.PutMediaBlock(ium);

				if ( rtn.offset == -1 )
				{
					this.iseof = true;
					return;
				}

				ium.media.offset = rtn.offset;
				ium.media.mid = rtn.mid;
				ium.media.filepath = rtn.filepath;
			}

			int cplen = ( Interface.BUFFER_LEN - offset > len-off-rlen ) ? ( len-off-rlen ):(Interface.BUFFER_LEN-offset);
			if ( b != null )
				System.arraycopy(b,off+rlen,this.buffer,offset,cplen);
			offset += cplen;
			rlen += cplen;
		}while ( rlen < len );
	}

	public void flush()
	{
		if ( offset == Interface.BUFFER_LEN )
		{
			ium.buffer = this.buffer;
			ium.bufferlen = offset;
			offset = 0;
			rtn = iface.PutMediaBlock(ium);

			if ( rtn.offset == -1 )
			{
				this.iseof = true;
				return;
			}

			ium.media.offset = rtn.offset;
			ium.media.mid = rtn.mid;
			ium.media.filepath = rtn.filepath;
		}else if ( offset > 0 )
		{
			ium.buffer = new byte[offset];
			ium.bufferlen = offset;
			offset = 0;
			System.arraycopy(this.buffer,0,ium.buffer,0,ium.bufferlen);
			rtn = iface.PutMediaBlock(ium);

			if ( rtn.offset == -1 )
			{
				this.iseof = true;
				return;
			}

			ium.media.offset = rtn.offset;
			ium.media.mid = rtn.mid;
			ium.media.filepath = rtn.filepath;
		}
	}

	public void close()
	{
		flush();
		ium.buffer = null;
		ium.bufferlen = 0;
		rtn = iface.PutMediaBlock(ium);
		this.iseof = true;
	}
}